package com.github.mall.common.services.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Dict;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.mall.common.dao.UmsAdminRoleRelationDao;
import com.github.mall.common.dao.UmsRoleDao;
import com.github.mall.common.entity.UmsAdminRoleRelationEntity;
import com.github.mall.common.entity.UmsRoleEntity;
import com.github.mall.common.services.UmsRoleService;
import com.github.mall.common.util.EntityUtils;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
@AllArgsConstructor
public class UmsRoleServiceImpl extends ServiceImpl<UmsRoleDao, UmsRoleEntity> implements UmsRoleService {

    private final UmsAdminRoleRelationDao umsAdminRoleRelationDao;

    private final UmsRoleDao umsRoleDao;

    @Override
    public List<UmsRoleEntity> getUserRoleList(String userId) {
        UmsAdminRoleRelationEntity umsAdminRoleRelationEntity = new UmsAdminRoleRelationEntity();
        umsAdminRoleRelationEntity.setAdminId(userId);
        return umsAdminRoleRelationDao
                .selectList(new QueryWrapper<>(umsAdminRoleRelationEntity))
                .stream()
                .map(e -> umsRoleDao.selectById(e.getRoleId()))
                .collect(Collectors.toList());
    }

    @Override
    public UmsRoleEntity addRole(Dict roleParam) {
        if (checkRoleIsExist(roleParam)) {
            UmsRoleEntity umsRoleEntity = EntityUtils.mapToEntity(roleParam, UmsRoleEntity.class);
            umsRoleEntity.setCreateTime(DateUtil.date());
            int flag = umsRoleDao.insert(umsRoleEntity);
            if (flag != 0) {
                return umsRoleEntity;
            }

        }

        return null;
    }

    @Override
    public boolean checkRoleIsExist(Dict roleParam) {
        UmsRoleEntity umsRoleEntity = EntityUtils.mapToEntity(roleParam, UmsRoleEntity.class);
        List roleList = umsRoleDao.selectList(new QueryWrapper<>(umsRoleEntity));
        if (roleList == null || roleList.size() == 0) {
            return true;
        }
        return false;
    }


}
